package com.boco.blch.runner.service;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.boco.blch.runner.command.Command;
import com.boco.blch.runner.command.CommandImpl;
import com.boco.blch.runner.command.MultipleCommand;
import com.boco.blch.runner.executor.CommandExecutor;
import com.boco.blch.runner.executor.MultipleCommandExecutor;
import com.boco.blch.runner.login.UserInfo;
import com.boco.blch.runner.parameter.SingleLoginParam;
import com.boco.blch.runner.result.MultipleResult;
import com.boco.blch.runner.result.Result;
import com.boco.blch.runner.result.ResultInfo;
import com.boco.blch.runner.result.handler.TrimResultForAIX;
import com.boco.blch.runner.util.ErrorMessageUtil;
import com.boco.blch.runner.util.ObjectUtil;

import net.sf.json.JSONArray;

public class ShellExecuteService {
	private static Logger logger = Logger.getLogger(ShellExecuteService.class);

	public String service(ModelMap modelMap, String Ip, Integer Port, String User, String UserEncryptd, String Password,
			String PasswordEncryptd, String ShellCommand) {
		UserInfo userInfo = new UserInfo(Ip, Port, User, Password);
		Command command = new CommandImpl(ShellCommand);
		Result ri;
		try {
			ri = new CommandExecutor(userInfo, command).execute();
			ri = new TrimResultForAIX().handler(ri);
		} catch (IOException e) {
			ri = new ResultInfo(false, 126, ErrorMessageUtil.getErrorMessageByErrorCode(126));
		} finally {
			try {
				userInfo.logout();
			} catch (IOException e) {
			}
		}
		String result = ObjectUtil.object2xml(ri);
		return result;
	}
	
	public static String connectTest(String Ip, Integer Port, String User, String Password){
		UserInfo userInfo = new UserInfo(Ip, Port, User, Password);
		try{
			userInfo.login();
			return "success";
		} catch(IOException e){
			return "failed";
		} finally {
			try {
				userInfo.logout();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	public static JSONArray execOnSingleLogin(SingleLoginParam slp){
		long now = System.currentTimeMillis();
		logger.info("接受到" + slp.getScriptcollection().size() + "个检查脚本请求,受检设备IP为:" + slp.getIp());
		UserInfo userInfo = new UserInfo(slp.getIp(), slp.getPort(), slp.getAccount(), slp.getPassword());
		MultipleCommand command = new MultipleCommand(slp.getScriptcollection());
		MultipleResult ri = null;
		try {
			ri = new MultipleCommandExecutor(userInfo, command).execute();
		} catch (IOException e) {
			e.printStackTrace();
			// TODO Auto-generated catch block
		} finally {
			try {
				userInfo.logout();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		logger.info("本次指令执行完毕，执行" + slp.getScriptcollection().size() + "个脚本，共耗时 " + (System.currentTimeMillis() - now) + "ms");	
		return ri.getResultArray();
	}
}
